﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.LIB.YJKControls;
using YJKArch.Utils;
using HYFamilyLibDataManager;

namespace YJKArch.ColumnModule
{
	public partial class DlgColumnInsert : System.Windows.Forms.Form
	{
		public int InsertType
		{
			get
			{
				return this.m_InsertType;
			}
		}

		public bool IsArchColumn
		{
			get
			{
				return this.m_IsArchColumn;
			}
		}

		public bool PickButton
		{
			get
			{
				return this.m_PickButton;
			}
			set
			{
				this.m_PickButton = value;
			}
		}

		public ElementId TopLevelId
		{
			get
			{
				return AssistFunc.GetLevelByName(this.m_docment, this.cmbTopLevel.SelectedItem.ToString()).Id;
			}
		}

		public double BottomOffset
		{
			get
			{
				if (!(this.tbBottomOffset.Text == ""))
				{
					return Convert.ToDouble(this.tbBottomOffset.Text);
				}
				return 0.0;
			}
		}

		public double TopOffset
		{
			get
			{
				if (!(this.tbTopOffset.Text == ""))
				{
					return Convert.ToDouble(this.tbTopOffset.Text);
				}
				return 0.0;
			}
		}

		public double XOffset
		{
			get
			{
				if (!(this.textBoxXoff.Text == ""))
				{
					return Convert.ToDouble(this.textBoxXoff.Text);
				}
				return 0.0;
			}
		}

		public double YOffset
		{
			get
			{
				if (!(this.textBoxYoff.Text == ""))
				{
					return Convert.ToDouble(this.textBoxYoff.Text);
				}
				return 0.0;
			}
		}

		public double Angle
		{
			get
			{
				if (!(this.textBoxAngle.Text == ""))
				{
					return Convert.ToDouble(this.textBoxAngle.Text);
				}
				return 0.0;
			}
		}

		public bool AutoRotate
		{
			get
			{
				return this.checkBoxAutoRotate.Checked;
			}
		}

		public DlgColumnInsert(UIApplication app)
		{
			try
			{
				this.m_application = app;
				this.m_docment = app.ActiveUIDocument.Document;
				this.archDB = FamilyLibDatabase.GetSqliteDB(SubjectType.Architecture, this.m_application.Application.VersionNumber);
				this.InitializeComponent();
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}

		public FamilySymbol GetColumnFamilySymbol()
		{
			if (this.archDB == null)
			{
				return null;
			}
			FamilySymbol result;
			try
			{
				IFamilyTable familyTable = this.archDB.FamilyTable;
				ITypeTable typeTable = this.archDB.TypeTable;
				DbFamily family = (DbFamily)this.cmbColFamily.SelectedItem;
				string name = this.cmbColType.SelectedItem.ToString();
				result = this.archDB.TypeTable[family, name].Create(this.m_docment);
			}
			catch (Exception)
			{
				result = null;
			}
			return result;
		}

		private void InitComboColFamily()
		{
			this.cmbColFamily.Items.Clear();
			if (this.archDB == null)
			{
				return;
			}
			string name = "建筑柱";
			if (!this.m_IsArchColumn)
			{
				name = "结构柱";
			}
			try
			{
				foreach (DbFamily item in this.archDB.CategoryTable[name].GetAllFamilies(true, CheckType.All))
				{
					this.cmbColFamily.Items.Add(item);
				}
				if (this.cmbColFamily.Items.Count > 0)
				{
					this.cmbColFamily.SelectedIndex = 0;
				}
			}
			catch
			{
			}
		}

		private void cmbColFamily_SelectionChangeCommitted(object sender, EventArgs e)
		{
			this.ResetCmbColType();
			if (this.cmbColType.Items.Count <= 0)
			{
				MessageBox.Show("所选柱子在族库中应至少有一种规格（尺寸）可供选择，请检查族库中相关柱子！", "盈建科提示");
				return;
			}
			this.GetSelectedColumnType();
			if (this.m_nColType == 3)
			{
				this.cmbTopLevel.Enabled = false;
			}
		}

		private void ResetCmbColType()
		{
			if (this.cmbColFamily.SelectedItem != null)
			{
				if (this.cmbColType.Items.Count > 0)
				{
					this.cmbColType.Items.Clear();
				}
				DbFamily dbFamily = (DbFamily)this.cmbColFamily.SelectedItem;
				this.pbPreview.Image = AssistFunc.ResizeImage((Bitmap)dbFamily.Image, this.pbPreview.Width, this.pbPreview.Height);
				List<string> symbols = dbFamily.Symbols;
				if (symbols.Count > 0)
				{
					for (int i = 0; i < symbols.Count; i++)
					{
						this.cmbColType.Items.Add(symbols[i]);
					}
					if (this.cmbColType.Items.Count > 0)
					{
						this.cmbColType.SelectedIndex = 0;
					}
				}
			}
		}

		private void checkBoxAutoRotate_CheckedChanged(object sender, EventArgs e)
		{
			this.textBoxAngle.Enabled = !this.textBoxAngle.Enabled;
		}

		private void radioBtnPtIns_MouseLeave(object sender, EventArgs e)
		{
			this.toolTip.Hide((RadioButton)sender);
		}

		private void radioBtnAxisIns_MouseLeave(object sender, EventArgs e)
		{
			this.toolTip.Hide((RadioButton)sender);
		}

		private void radioBtnRectIns_MouseLeave(object sender, EventArgs e)
		{
			this.toolTip.Hide((RadioButton)sender);
		}

		private void btnLoadFamily_Click(object sender, EventArgs e)
		{
			base.Hide();
			if (AssistFunc.LoadStandardFamily(this.m_application))
			{
				this.InitComboColFamily();
			}
			base.Show();
		}

		private void btnNewType_Click(object sender, EventArgs e)
		{
			if (this.cmbColFamily.SelectedIndex < 0)
			{
				return;
			}
			string currentFamilySymbolName = this.cmbColType.SelectedItem.ToString();
			DbFamily dbFamily = (DbFamily)this.cmbColFamily.SelectedItem;
			List<string> symbols = dbFamily.Symbols;
			List<ParameterData> list = new List<ParameterData>();
			if (!this.GetParameterData(ref list))
			{
				return;
			}
			if (list.Count == 0)
			{
				MessageBox.Show("无有效尺寸参数（缺少尺寸参数或者参数分组错误）", "盈建科提示");
				return;
			}
			using (DlgNewSize dlgNewSize = new DlgNewSize(currentFamilySymbolName, symbols, list))
			{
				if (dlgNewSize.ShowDialog() == DialogResult.OK)
				{
					string newTypeName = dlgNewSize.NewTypeName;
					DataTable dataTable = dbFamily.Database.TypeTable.DataTable(dbFamily);
					dataTable.Clear();
					DataRow dataRow = dataTable.NewRow();
					dataRow["规格名"] = newTypeName;
					foreach (ParameterData parameterData in list)
					{
						dataRow[parameterData.ParName] = AssistFunc.feetToMM(parameterData.ParValue);
					}
					dataTable.Rows.Add(dataRow);
					dbFamily.AddType(dataTable);
					this.ResetCmbColType();
					if (this.cmbColType.Items.Count > 0)
					{
						this.cmbColType.SelectedIndex = this.cmbColType.Items.Count - 1;
					}
				}
			}
		}

		private bool GetParameterData(ref List<ParameterData> parameterDataList)
		{
			DbFamily dbFamily = (DbFamily)this.cmbColFamily.SelectedItem;
			if (dbFamily == null)
			{
				return false;
			}
			if (this.archDB == null)
			{
				return false;
			}
			string name = this.cmbColType.SelectedItem.ToString();
			DbFamilySymbol dbFamilySymbol = this.archDB.TypeTable[dbFamily, name];
			if (dbFamilySymbol == null)
			{
				return false;
			}
			foreach (DbParameter dbParameter in dbFamilySymbol.Params)
			{
                if ((int)dbParameter.ParamDefinition.BuiltInParameterGroup == -5000101)
				{
					double parValue = 0.0;
					try
					{
						parValue = AssistFunc.mmToFeet(Convert.ToDouble(dbParameter.Value.ToString()));
					}
					catch (Exception)
					{
						continue;
					}
					ParameterData item = new ParameterData(dbParameter.ParamDefinition.Name, parValue);
					parameterDataList.Add(item);
				}
			}
			return true;
		}

		private int GetSelectedColumnType()
		{
			DbFamily dbFamily = (DbFamily)this.cmbColFamily.SelectedItem;
			if (dbFamily == null)
			{
				return 0;
			}
			if (this.archDB == null)
			{
				return 0;
			}
			string name = this.cmbColType.SelectedItem.ToString();
			DbFamilySymbol dbFamilySymbol = this.archDB.TypeTable[dbFamily, name];
			if (dbFamilySymbol == null)
			{
				return 0;
			}
			foreach (DbParameter dbParameter in dbFamilySymbol.Params)
			{
				string name2 = dbParameter.ParamDefinition.Name;
				if (name2 == "宽度" || name2 == "深度" || name2 == "Width" || name2 == "Depth")
				{
					this.m_nColType = 1;
				}
				if (name2 == "直径" || name2 == "Diameter")
				{
					this.m_nColType = 2;
				}
				if (name2.Contains("高度"))
				{
					this.m_nColType = 3;
				}
			}
			return this.m_nColType;
		}

		private bool NewTypeExist(string newTypeName)
		{
			for (int i = 0; i < this.cmbColType.Items.Count; i++)
			{
				if (this.cmbColType.GetItemText(this.cmbColType.Items[i]).CompareTo(newTypeName) == 0)
				{
					return true;
				}
			}
			return false;
		}

		private void SaveColumnData()
		{
			FileStream fileStream = new FileStream(Path.GetTempPath() + "DlgColumnInsert.dat", FileMode.Create);
			StreamWriter streamWriter = new StreamWriter(fileStream);
			streamWriter.WriteLine(this.rdbArch.Checked);
			streamWriter.WriteLine(this.m_InsertType.ToString());
			streamWriter.WriteLine(this.cmbColFamily.SelectedItem.ToString());
			streamWriter.WriteLine(this.cmbColType.SelectedItem.ToString());
			streamWriter.WriteLine(this.cmbTopLevel.SelectedItem.ToString());
			streamWriter.WriteLine(this.textBoxXoff.Text);
			streamWriter.WriteLine(this.textBoxYoff.Text);
			streamWriter.WriteLine(this.textBoxAngle.Text);
			streamWriter.WriteLine(this.checkBoxAutoRotate.Checked.ToString());
			streamWriter.WriteLine(this.tbBottomOffset.Text);
			streamWriter.WriteLine(this.tbTopOffset.Text);
			streamWriter.WriteLine(base.Location.X);
			streamWriter.WriteLine(base.Location.Y);
			streamWriter.Flush();
			streamWriter.Close();
			fileStream.Close();
		}

		private bool ReadDataByProjectSetting()
		{
			string s = Assist.FileUtil.GetDataFromConfigFile(Assist.FileUtil.GetProjConfigFile(this.m_docment).FullName, "全局配置", "柱样式").Trim();
			if (this.cmbColFamily.FindString(s) >= 0)
			{
				this.cmbColFamily.SelectedIndex = this.cmbColFamily.FindString(s);
			}
			else
			{
				this.cmbColFamily.SelectedIndex = 0;
			}
			return true;
		}

		private bool ReadColumnData()
		{
			string path = Path.GetTempPath() + "DlgColumnInsert.dat";
			if (!File.Exists(path))
			{
				base.StartPosition = FormStartPosition.CenterScreen;
				this.m_IsArchColumn = true;
				this.rdbArch.Checked = this.m_IsArchColumn;
				this.rdbStructure.Checked = !this.m_IsArchColumn;
				this.InitializeData();
				return this.ReadDataByProjectSetting();
			}
			FileStream fileStream = new FileStream(path, FileMode.Open);
			StreamReader streamReader = new StreamReader(fileStream);
			streamReader.BaseStream.Seek(0L, SeekOrigin.Begin);
			this.m_IsArchColumn = Convert.ToBoolean(streamReader.ReadLine());
			this.rdbArch.Checked = this.m_IsArchColumn;
			this.rdbStructure.Checked = !this.m_IsArchColumn;
			string text = streamReader.ReadLine();
			this.m_InsertType = Convert.ToInt32(text);
			if (this.m_InsertType == 0)
			{
				this.tsbPick.Checked = true;
				this.tsbAxis.Checked = false;
				this.tsbRect.Checked = false;
			}
			else if (this.m_InsertType == 1)
			{
				this.tsbPick.Checked = false;
				this.tsbAxis.Checked = true;
				this.tsbRect.Checked = false;
			}
			else if (this.m_InsertType == 2)
			{
				this.tsbPick.Checked = false;
				this.tsbAxis.Checked = false;
				this.tsbRect.Checked = true;
			}
			this.InitComboColFamily();
			text = streamReader.ReadLine();
			if (this.cmbColFamily.FindString(text) >= 0)
			{
				this.cmbColFamily.SelectedIndex = this.cmbColFamily.FindString(text);
			}
			else if (this.cmbColFamily.Items.Count > 0)
			{
				this.cmbColFamily.SelectedIndex = 0;
			}
			this.ResetCmbColType();
			text = streamReader.ReadLine();
			if (this.cmbColType.FindString(text) >= 0)
			{
				this.cmbColType.SelectedIndex = this.cmbColType.FindString(text);
			}
			else if (this.cmbColType.Items.Count > 0)
			{
				this.cmbColType.SelectedIndex = 0;
			}
			this.InitializeLevelData();
			text = streamReader.ReadLine();
			if (this.cmbTopLevel.Items.Count > 1)
			{
				this.cmbTopLevel.SelectedIndex = 1;
			}
			else if (this.cmbTopLevel.Items.Count == 1)
			{
				this.cmbTopLevel.SelectedIndex = 0;
			}
			text = streamReader.ReadLine();
			this.textBoxXoff.Text = text;
			text = streamReader.ReadLine();
			this.textBoxYoff.Text = text;
			text = streamReader.ReadLine();
			this.textBoxAngle.Text = text;
			text = streamReader.ReadLine();
			this.checkBoxAutoRotate.Checked = Convert.ToBoolean(text);
			try
			{
				text = streamReader.ReadLine();
				if (text.CompareTo("") != 0)
				{
					this.tbBottomOffset.Text = text;
				}
				text = streamReader.ReadLine();
				if (text.CompareTo("") != 0)
				{
					this.tbTopOffset.Text = text;
				}
				base.StartPosition = FormStartPosition.Manual;
				int x = Convert.ToInt32(streamReader.ReadLine());
				int y = Convert.ToInt32(streamReader.ReadLine());
				base.Location = new System.Drawing.Point(x, y);
			}
			catch (Exception)
			{
				this.tbBottomOffset.Text = "0";
				this.tbTopOffset.Text = "0";
				streamReader.Close();
				fileStream.Close();
				return true;
			}
			streamReader.Close();
			fileStream.Close();
			return true;
		}

		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		private void SendSetFocusMessage()
		{
		}

		[DllImport("user32.dll")]
		public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

		private void ClickESC()
		{
			int bVk = 27;
			int dwFlags = 0;
			int dwFlags2 = 2;
			DlgColumnInsert.keybd_event((byte)bVk, 0, dwFlags, 0);
			DlgColumnInsert.keybd_event((byte)bVk, 0, dwFlags2, 0);
		}

		private void DlgColumnInsert_MouseLeave(object sender, EventArgs e)
		{
			if (!base.ClientRectangle.Contains(base.PointToClient(Cursor.Position)))
			{
				this.SendSetFocusMessage();
				return;
			}
			base.Focus();
		}

		private void tsbPick_Click(object sender, EventArgs e)
		{
			this.m_InsertType = 0;
			this.m_PickButton = true;
			this.tsbPick.Checked = true;
			this.tsbAxis.Checked = false;
			this.tsbRect.Checked = false;
			this.SendSetFocusMessage();
			this.ClickESC();
		}

		private void tsbAxis_Click(object sender, EventArgs e)
		{
			this.m_InsertType = 1;
			this.m_PickButton = true;
			this.tsbPick.Checked = false;
			this.tsbAxis.Checked = true;
			this.tsbRect.Checked = false;
			this.SendSetFocusMessage();
			this.ClickESC();
		}

		private void tsbRect_Click(object sender, EventArgs e)
		{
			this.m_InsertType = 2;
			this.m_PickButton = true;
			this.tsbPick.Checked = false;
			this.tsbAxis.Checked = false;
			this.tsbRect.Checked = true;
			this.SendSetFocusMessage();
			this.ClickESC();
		}

		private void InitializeData()
		{
			this.InitComboColFamily();
			this.ResetCmbColType();
			this.InitializeLevelData();
		}

		private void InitializeLevelData()
		{
			this.cmbTopLevel.Items.Clear();
			Level currentViewLevel = AssistFunc.GetCurrentViewLevel(this.m_docment);
			List<Level> sortLevels = Common.GetSortLevels(this.m_docment, double.MinValue, double.MaxValue);
			foreach (Level level in sortLevels)
			{
				if (currentViewLevel != null)
				{
					if (Geometry.Lessthan_Or_Equal(currentViewLevel.Elevation, level.Elevation) || sortLevels.Count == 1)
					{
						this.cmbTopLevel.Items.Add(level.Name);
					}
				}
				else
				{
					this.cmbTopLevel.Items.Add(level.Name);
				}
			}
			if (this.cmbTopLevel.Items.Count == 0)
			{
				return;
			}
			if (this.cmbTopLevel.Items.Count > 1)
			{
				this.cmbTopLevel.SelectedIndex = 1;
				return;
			}
			this.cmbTopLevel.SelectedIndex = 0;
		}

		private void DlgColumnInsert_Load(object sender, EventArgs e)
		{
			this.ReadColumnData();
		}

		private void DlgColumnInsert_FormClosing(object sender, FormClosingEventArgs e)
		{
			this.SaveColumnData();
		}

		private void rdbArch_CheckedChanged(object sender, EventArgs e)
		{
			this.m_IsArchColumn = this.rdbArch.Checked;
			this.InitializeData();
		}

		private void DlgColumnInsert_FormClosed(object sender, FormClosedEventArgs e)
		{
			this.ClickESC();
		}

		private void tbBottomOffset_TextChanged(object sender, EventArgs e)
		{
			if (!Common.IsValidating(this.tbBottomOffset.Text, -1000.0, 1000.0))
			{
				this.tbBottomOffset.Text = "0";
			}
		}

		private void tbTopOffset_TextChanged(object sender, EventArgs e)
		{
			if (!Common.IsValidating(this.tbTopOffset.Text, -1000.0, 1000.0))
			{
				this.tbTopOffset.Text = "0";
			}
		}

		private void textBoxXoff_TextChanged(object sender, EventArgs e)
		{
			if (!Common.IsValidating(this.textBoxXoff.Text, -1000.0, 1000.0))
			{
				this.textBoxXoff.Text = "0";
			}
		}

		private void textBoxAngle_TextChanged(object sender, EventArgs e)
		{
			if (!Common.IsValidating(this.textBoxAngle.Text, 0.0, 360.0))
			{
				this.textBoxAngle.Text = "0";
			}
		}

		private void textBoxYoff_TextChanged(object sender, EventArgs e)
		{
			if (!Common.IsValidating(this.textBoxYoff.Text, -1000.0, 1000.0))
			{
				this.textBoxYoff.Text = "0";
			}
		}

		private UIApplication m_application;

		private Document m_docment;

		private FamilyLibDatabase archDB;

		private int m_InsertType;

		private bool m_IsArchColumn = true;

		private int m_nColType = 1;

		private bool m_PickButton;
	}
}
